<?php

/**
 * 发布产品添加自定义字段
 */
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
 
    $field['id']            = 'product_sub_title';
    $field['placeholder']   = '产品标题';
    $field['label']         = __('产品标题', 'woocommerce' );
    $field['description']   = __('定义该字段的原因为让产品名称用于SEO.', 'woocommerce');
    $field['desc_tip']      = true;
    
    echo '<div class="options_group">';
    woocommerce_wp_text_input($field);
    echo '</div>';
}

/**
 * 保存自定义字段
 */
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save');
function woo_add_custom_general_fields_save($post_id){
    $woocommerce_product_sub_title = $_POST['product_sub_title'];
    if(!empty($woocommerce_product_sub_title)){
        update_post_meta($post_id, 'product_sub_title', esc_attr($woocommerce_product_sub_title));
    }
}


/**
 * 重新定义分类页产品标题函数
 */
function woocommerce_template_loop_product_title() {

    $product_sub_title = get_post_meta(get_the_ID(), 'product_sub_title', true);
    if ($product_sub_title) {
        $title = $product_sub_title;
    }else{
        $title = get_the_title();
    }
    echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . $title . '</h2>';
}
